package com.freely.data.rxBus

import io.reactivex.subjects.Subject

/**
 * @author DaWan
 * @time 2018/12/15 12:06
 * @description
 */
class RxBus private constructor() {
    private val publisherMap = mutableMapOf<Int, Subject<Any>>()
    private val noPublisherException = RuntimeException("no publisher")

    fun post(k: Int, objects: Any) {
        val bus = publisherMap[k] ?: throw noPublisherException
        bus.onNext(objects)
    }

    fun register(publisherName: Int, publisher: Subject<Any>) {
        publisherMap[publisherName] = publisher
    }

    fun cancellation(publisherName: Int) {
        publisherMap.remove(publisherName)
    }

    fun toObservable(publisherName: Int) =
            publisherMap[publisherName] ?: throw noPublisherException

    fun <T> toObservable(publisherName: Int, type: Class<T>) =
            publisherMap[publisherName]?.ofType(type) ?: throw noPublisherException

    fun hasObservable(publisherName: Int) =
            publisherMap[publisherName]?.hasObservers() ?: throw noPublisherException

    private object SingleHolder {
        val holder = RxBus()
    }

    companion object {
        val instance = SingleHolder.holder
    }

}